#pragma once
#include<iostream>
#include<sys/socket.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<string>
#include<cstring>


//网络地址和主机地址转换的类

namespace InetAddrModule
{
  class InetAddr
  {
  public:
    InetAddr(const struct sockaddr_in &addr)
        : _addr(addr)
    {
      // 把从网络中拿到的端口和IP转成主机风格
      _port = ntohs(_addr.sin_port);
      //_ip = inet_ntoa(_addr.sin_addr); // 4字节网络ip转换为点分十进制字符串
      char ipbuffer[1024];
      inet_ntop(AF_INET, &_addr.sin_addr, ipbuffer, sizeof(ipbuffer));//相比较inet_ntoa是线程安全的
      _ip = ipbuffer;
    }

    InetAddr(uint16_t port) :_port(port)
    {
       //主机转网络
       memset(&_addr, 0, sizeof(_addr));
       _addr.sin_family = AF_INET;
       _addr.sin_port = htons(_port);
      _addr.sin_addr.s_addr = INADDR_ANY;
    }


    InetAddr(const std::string& ip, uint16_t port) :_ip(ip), _port(port)
    {
      //主机地址转换为网络地址
      memset(&_addr, 0, sizeof(_addr));
      _addr.sin_family = AF_INET;
      inet_pton(AF_INET, _ip.c_str(), &_addr.sin_addr); 
      _addr.sin_port = htons(_port);
    }
    

    std::string IP() { return _ip; }
    uint16_t Port() { return _port; }
    const struct sockaddr_in& NetAddr(){return _addr;}
    bool operator==(const InetAddr& addr)
    {
      return addr._ip == _ip && addr._port == _port;
    }

    std::string StringAddr()
    {
      return _ip + ":" +std::to_string(_port);
    }
    std::string StringAddr() const
    {
      return _ip + ":" +std::to_string(_port);
    }
    const struct sockaddr* NetAddrPtr()
    {
        return CONV(_addr);
    }
    socklen_t NetAddrLen()
    {
       return sizeof(_addr);
    }
    ~InetAddr() {}

  private:
    struct sockaddr_in _addr;
    std::string _ip;
    uint16_t _port;
  };
} // namespace InetAddrModule
